package util;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.DhcpInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.List;
import java.util.Random;

import data.SharedPreferencesUtils;


/**
 * Created by Administrator on 2016/7/22.
 * 获取手机或者app的相关信息
 */
public class getInformation {
    private Context mContext;
    private static getInformation mGetInformation;

    private getInformation(Context context){
        this.mContext = context.getApplicationContext();
    }
    public static getInformation getNewGetInformation(Context context){
        if(mGetInformation == null){
            synchronized (getInformation.class){
                if(mGetInformation == null){
                    mGetInformation = new getInformation(context);
                }
            }

        }
        return mGetInformation;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    int dip2px(float dpValue) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,

                dpValue, mContext.getResources().getDisplayMetrics());
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public int px2dip( float pxValue) {
        final float scale = mContext.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 获取DisplayMetrics对象
     */
    DisplayMetrics getIWidth(){
        //得到屏幕宽度
        DisplayMetrics dm = new DisplayMetrics();
        dm = mContext.getApplicationContext().getResources().getDisplayMetrics();
        Log.e("bitmapWidh","   手机的dpi   " +dm.densityDpi);
        return dm;
    }

    /**
     * 获取DisplayMetrics对象
     */
    public int getPhoneDIP(Context context){
        int dip = (int)context.getResources().getDisplayMetrics().density;
        return dip;
    }

    /**
     * 获取手机的高度
     */
    public int getIHeight(Context context){
        //得到屏幕高度
        WindowManager wm =  ((Activity)context).getWindowManager();
        return wm.getDefaultDisplay().getHeight();
    }

    /**
     * 获取版本号
     */
    public String getVersion(){
        PackageManager manager = mContext.getPackageManager();
        PackageInfo info = null;
        try {
            info = manager.getPackageInfo(mContext.getPackageName(), 0);
            return info.versionName;
        } catch (PackageManager.NameNotFoundException e) {e.printStackTrace();}
        return "";
    }

    /**
     * 获取手机链接的 链接热点
     */
    public String getIHotpot(Context context){
        //mPhoneType = Build.MODEL;
        WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);        //获得系统wifi服务
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        //判断是否开启wifi
        if(wifiManager.isWifiEnabled()){
          return wifiInfo.getSSID();
        }
        return null;
    }

    /**
     *手机型号品牌
     */
    public String getInfoPhone() {
        return android.os.Build.BRAND;
    }

    /**
     *手机型号
     */
    public String getInfoPhoneType() {
        return  android.os.Build.MODEL;
    }

    /**
     * 获取当前应用程序的包名
     * @return 返回包名
     */
    public String getAppProcessName() {
        //当前应用pid
        int pid = android.os.Process.myPid();
        //任务管理类
        ActivityManager manager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        //遍历所有应用
        List<ActivityManager.RunningAppProcessInfo> infos = manager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo info : infos) {
            if (info.pid == pid)//得到当前应用
                return info.processName;//返回包名
        }
        return "";
    }

    /**
     * 网关
     */
    public String getGateWay(){
        WifiManager wifiManager = ((WifiManager)mContext.getSystemService(Context.WIFI_SERVICE));
        DhcpInfo dhcpInfo = wifiManager.getDhcpInfo();
        if(dhcpInfo ==null){
            return "";
        }
        long getewayIpL = dhcpInfo.gateway;
       return getWay(getewayIpL);
    }

    private String getWay(long ip){
       StringBuffer sb=new StringBuffer();
       sb.append(String.valueOf((int)(ip&0xff)));
       sb.append('.');
       sb.append(String.valueOf((int)((ip>>8)&0xff)));
       sb.append('.');
       sb.append(String.valueOf((int)((ip>>16)&0xff)));
       sb.append('.');
       sb.append(String.valueOf((int)((ip>>24)&0xff)));
       return sb.toString();
    }

    /**
     * 获取设备IP
     */
    public String getI_IP() {
        try {
            WifiManager wifimanage = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);//获取WifiManager
            //检查wifi是否开启
            if (!wifimanage.isWifiEnabled()) {
                return "";
            }
            WifiInfo wifiinfo = wifimanage.getConnectionInfo();
            String ip = intToIp(wifiinfo.getIpAddress());
            if(ip.equals("")||ip.equals("0.0.0.0")){
                return "";
            }else {
               return ip;
            }
        }catch (Exception e){
            return "";
        }
    }

    /**
     * 将获取的int转为真正的ip地址,参考的网上的，修改了下
     */
    private String intToIp(int i)  {
        return (i & 0xFF)+ "." + ((i >> 8 ) & 0xFF) + "." + ((i >> 16 ) & 0xFF) +"."+((i >> 24 ) & 0xFF );
    }

    /**
     *获取wifi 的mac   获取被连接网络的mac地址
     */
    public String getWiFiMac(){
        try {
            WifiManager wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
            if(!wifi.isWifiEnabled()){
                return "";
            }
            WifiInfo info = wifi.getConnectionInfo();
            return info.getBSSID();
        }catch (Exception e){
            return "";
        }
    }

    /**
     * 获取设备 MAC(1)  获得本机的MAC地址
     */
    public String getIMAC(){
        try{
            String mac = (String) SharedPreferencesUtils.getParam(mContext,HomeUtil.mFWQMAC,"");
            if(mac.equals("") || mac.equals("02:00:00:00:00:00") || mac.equals("00:00:00:00:00:00")){
                WifiManager wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
                WifiInfo info = wifi.getConnectionInfo();
                String getMac = info.getMacAddress();
                if( !getMac.equals("") && !getMac.equals("02:00:00:00:00:00") && !getMac.equals("00:00:00:00:00:00")){
                  return getMac;
                }else {
                    getMac = getProcessMAC();
                    if(getMac !=null &&!getMac.equals("") && !getMac.equals("02:00:00:00:00:00") && !getMac.equals("00:00:00:00:00:00")){
                       return getMac;
                    }else {
                        return "";
                    }
                }
            }else {
                return mac;
            }
        }catch (Exception e){
            return "";
        }

    }

    /**
     * 获取设备 MAC(2)
     */
    private String getProcessMAC(){
        String str = "";
        try {
            Process pp = Runtime.getRuntime().exec(
                    "cat /sys/class/net/wlan0/address ");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            for (; null != str;) {
                str = input.readLine();
                if (str != null) {
                    return str.trim();// 去空格获取设备MAC
                }
            }
        } catch (IOException ex) {
            // 赋予默认值
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 获取wifi名称
     */
    public String getWIFIName(){
        try{
            WifiManager wifiMgr = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
            WifiInfo info = wifiMgr.getConnectionInfo();
            if(info != null){
                String wifiId = info.getSSID();
                if(!wifiId.equals("") && wifiId.length() > 0){
                    String wifiName = wifiId.substring(0,wifiId.length());
                    if(!wifiName.equals("") && wifiName.length() > 1){
                        if(wifiName.substring(0,1).equals("\"")){
                            String wifi = wifiName.substring(1,wifiName.length()-1);
                            return wifi;
                        }else {
                            return wifiName;
                        }
                    }else {
                        return "";
                    }
                }else {
                    return "";
                }
            }else {
                return "";
            }
        }catch (Exception e){
            return "";
        }
    }

    /**
     * 生成一个mac
     */
    public String generateMac(){
        StringBuffer mac = new StringBuffer();
        String macString = getStringRandom(12);
        LogUtil.eE("",macString);
        for (int i = 0; i < 6; i++) {
            if(i == 5){
                mac.append(macString.substring(2*i,2*i+2));
            }else {
                mac.append(macString.substring(2*i,2*i+2)+":");
            }

        }
        return mac.toString();
    }

    /**
     *
     * @return IMEI 是国际移动设备身份码的缩写
     */
    public String getAndroidPhoneID(Context context){
        TelephonyManager TelephonyMgr = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        String szImei = TelephonyMgr.getDeviceId();
        LogUtil.eE("",szImei);
        return szImei;
    }

    /**
     * android 设备的id 重置时会变化
     * @param context 上下文
     * @return String
     */
    public String getAndroidID(Context context){
        String androidID = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID)+"";
        LogUtil.eE("",androidID);
        return androidID;
    }

    /**
     * IMEI 和 id 的MD5值
     * @return stirng
     */
    public String getAndroidMD5(){
        String stringMd5 = StringUtil.getStringUtilNew().getMD5String(getAndroidPhoneID(mContext)+getAndroidID(mContext));
        LogUtil.eE("",stringMd5);
        return stringMd5;
    }

    private static void append(StringBuffer stringBuffer, String text) {
        if (stringBuffer != null) {
            stringBuffer.append(text + "\n");
        }
    }

    //生成随机数字和字母,
    public String getStringRandom(int length) {

        String val = "";
        Random random = new Random();

        //参数length，表示生成几位随机数
        for(int i = 0; i < length; i++) {

            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if( "char".equalsIgnoreCase(charOrNum) ) {
                //输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char)(random.nextInt(26) + temp);
            } else if( "num".equalsIgnoreCase(charOrNum) ) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val.toLowerCase();
    }



    /**
     * 目前是上网接口的回掉
     * 定义接口 用于itme  的回调
     */
    public interface OnIpClickListener {
        void onItemClick(String ip);
    }
}
